package com.codefarm.phone.mtsh.doctor.util;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;

import com.codefarm.phone.mtsh.doctor.Constant;
import com.codefarm.phone.mtsh.doctor.bean.BeanPerson;
import com.gzedu.android.lib.utils.StringUtil;

import fay.frame.fast.F;
import fay.frame.fast.callback.AjaxCallback;
import fay.frame.fast.callback.AjaxStatus;
import fay.frame.service.S;
import fay.frame.ui.U;

/**
 * 用户
 * 
 * @Title: UserManager.java
 * @Package com.gzedu.iqismobile.util
 * @Description: 用户管理
 * @company: 代码农场
 * @author : Eriksson
 * @date 2014-7-29 下午3:58:41
 * @version V1.0
 */
public class UserManager {
	/**
	 * 学员信息更新
	 * 
	 * @param context
	 * @param beanPerson
	 * @param callback
	 */
	public static void update(final Context context, BeanPerson beanPerson, final Callback<BeanPerson> callback) {
		if (context == null || callback == null) {
			return;
		}
		final BeanPerson _localBeanPerson = getLoginUserInfo(context);
		if (beanPerson == null || !StringUtil.isNotEmpty(beanPerson.getUserId())) {
			callback.callback(context, Constant.MESSAGE.INVALID_DATA, null);
		}
		F _f = new F(context);
		Map<String, String> _json = new HashMap<String, String>();
		_json.put(BeanPerson.PARAM_USER_ID, beanPerson.getUserId());
		if (StringUtil.isNotEmpty(beanPerson.getMobilePhone())) {
			_json.put(BeanPerson.PARAM_MOBILE_PHONE, beanPerson.getMobilePhone());
			_localBeanPerson.setMobilePhone(beanPerson.getMobilePhone());
		}
		if (StringUtil.isNotEmpty(beanPerson.getEmail())) {
			_json.put(BeanPerson.PARAM_EMAIL, beanPerson.getEmail());
			_localBeanPerson.setEmail(beanPerson.getEmail());
		}
		if (StringUtil.isNotEmpty(beanPerson.getCorrAddress())) {
			_json.put(BeanPerson.PARAM_CORR_ADDRESS, beanPerson.getCorrAddress());
			_localBeanPerson.setCorrAddress(beanPerson.getCorrAddress());
		}
		Map<String, Object> _param = new HashMap<String, Object>();
		_param.put("formMap.parameters", StringUtil.urlEncode(new JSONObject(_json).toString(), "utf-8"));
		if (beanPerson.getPhotoPathFile() != null) {
			Log.e("TAG", "图片的路径为:" + beanPerson.getPhotoPathFile());
			_param.put(BeanPerson.PARAM_PHOTO_PATH, beanPerson.getPhotoPathFile());
		}
		AjaxCallback<String> _callback = new AjaxCallback<String>() {
			@Override
			public void callback(String paramString, String paramT, AjaxStatus paramAjaxStatus) {
				super.callback(paramString, paramT, paramAjaxStatus);
				
				
				if (StringUtil.isNotEmpty(paramT) && callback != null) {
					try {
						// paramT = GzipUtil.unCompress(paramT);
						paramT = StringUtil.urlDecode(paramT, "utf-8");
						Log.e("TAG", "返回结果:" + paramT);
						JSONObject _json = new JSONObject(paramT);
						if (Constant.CODE.STATUS_Y.equals(_json.getString(Constant.KEY.STATUS))) {
							// _localBeanPerson.setPhotoPath(_json.getString(BeanPerson.COLUMN_PHOTO_PATH)+"?rnd="+Math.random());
							//json 判断关键字是否为空
							if (_json.has(BeanPerson.COLUMN_PHOTO_PATH)) {
								_localBeanPerson.setPhotoPath(_json.getString(BeanPerson.COLUMN_PHOTO_PATH));
							}
							saveUserInfo(context, _localBeanPerson);
							// TODO:将来可能会有更新后的头像返回地址.
							callback.callback(context, Constant.MESSAGE.OPERATION_COMPLETED, _localBeanPerson);
						} else {
							callback.callback(context, Constant.MESSAGE.OPERATION_FAILD, null);
						}
					} catch (JSONException e) {
						e.printStackTrace();
						Log.e("UserManager.update->callback", e.getMessage());
						callback.callback(context, Constant.MESSAGE.OPERATION_FAILD, null);
						return;
					}
				} else {
					callback.callback(context, Constant.MESSAGE.OPERATION_FAILD, null);
					return;
				}
			}
		};
		ProgressDialog _progressDialog =  U.Dialog(context).showWait();
		_progressDialog.setMessage(Constant.MESSAGE.SUBMITING);
		_f.progress(_progressDialog).ajax(Constant.INTERFACE.USER_UPDATE, _param, String.class, _callback);
	}

	/**
	 * 用户回调接口
	 * 
	 * @Title: UserManager.java
	 * @Package com.gzedu.iqismobile.util
	 * @Description: TODO
	 * @company: EE教育有限公司
	 * @author : Eriksson
	 * @date 2014-7-31 上午10:59:09
	 * @version V1.0
	 */
	public interface Callback<T> {
		public void callback(Context context, String message, T result);
	}

	/**
	 * 登陆
	 * 
	 * @param context
	 * @param userCode
	 * @param password
	 * @param callback
	 */
	public static void login(final Context context, String userCode, String password,
			final Callback<BeanPerson> callback) {
		if (context == null || callback == null) {
			return;
		}
		if (!StringUtil.isNotEmpty(userCode)) {
			callback.callback(context, Constant.MESSAGE.USER_CODE_IS_NOT_EMPTY, null);
			return;
		}
		if (!StringUtil.isNotEmpty(password)) {
			callback.callback(context, Constant.MESSAGE.PASSWORD_IS_NOT_EMPTY, null);
			return;
		}
		F _f = new F(context);
		S.init(context);
		Map<String, String> _json = new HashMap<String, String>();
		_json.put(BeanPerson.PARAM_USER_CODE, userCode);
		_json.put(BeanPerson.PARAM_USER_PASSWROD, password);
		Map<String, String> _param = new HashMap<String, String>();
		_param.put("formMap.parameters", StringUtil.urlEncode(new JSONObject(_json).toString(), "utf-8"));
		AjaxCallback<String> _callback = new AjaxCallback<String>() {
			@Override
			public void callback(String paramString, String paramT, AjaxStatus paramAjaxStatus) {
				super.callback(paramString, paramT, paramAjaxStatus);
				if (StringUtil.isNotEmpty(paramT) && callback != null) {
					try {
						paramT = StringUtil.urlDecode(paramT, "utf-8");
						// paramT = GzipUtil.unCompress(paramT);
						JSONObject _json = new JSONObject(paramT);
						BeanPerson _bean = parseBeanPerson(_json);
						saveUserInfo(context, _bean);
						if (_bean == null || !_bean.isLogin()) {
							callback.callback(context, Constant.MESSAGE.USER_CODE_OR_PASSWORD_FAILD, null);
						} else {
							callback.callback(context, Constant.MESSAGE.LOGIN_COMPLETED, _bean);
						}
					} catch (JSONException e) {
						e.printStackTrace();
						Log.e("UserManager.login->callback", e.getMessage());
						callback.callback(context, Constant.MESSAGE.LOGIN_FAILD, null);
						return;
					}
				}
			}
		};
		_f.ajax(Constant.INTERFACE.LOGIN, _param, String.class, _callback);
	}

	/**
	 * 登出
	 * 
	 * @return
	 */
	public static boolean logout(Context context) {
		return context.getSharedPreferences(Constant.KEY.LOCAL_LOGIN_USER_INFO, Context.MODE_PRIVATE).edit().clear()
				.commit();
	}

	/**
	 * 将JsonObject转为用户实体
	 * 
	 * @param json
	 * @return
	 */
	public static BeanPerson parseBeanPerson(JSONObject json) {
		if (json == null) {
			return null;
		}
		BeanPerson _bean = null;
		try {
			_bean = new BeanPerson();
			_bean.setLogin(json.getString(BeanPerson.COLUMN_LOGIN));
			_bean.setUserId(json.getString(BeanPerson.COLUMN_USER_ID));
			_bean.setRealname(json.getString(BeanPerson.COLUMN_REALNAME));
			_bean.setUserCode(json.getString(BeanPerson.COLUMN_USER_CODE));
			_bean.setTeacherId(json.getString(BeanPerson.COLUMN_TEACHER_ID));
			_bean.setGrade(json.getString(BeanPerson.COLUMN_GRADE));
			_bean.setMobilePhone(json.getString(BeanPerson.COLUMN_MOBILE_PHONE));
			_bean.setEmail(json.getString(BeanPerson.COLUMN_EMAIL));
			_bean.setCorrAddress(json.getString(BeanPerson.COLUMN_CORR_ADDRESS));
			_bean.setPhotoPath(json.getString(BeanPerson.COLUMN_PHOTO_PATH));
			_bean.setSubject(json.getString(BeanPerson.COLUMN_SUBJECT));
		} catch (JSONException e) {
			e.printStackTrace();
			Log.e("UserManager.BeanPerson", e.getMessage());
		}
		return _bean;
	}

	/**
	 * 本地化登陆用户信息
	 * 
	 * @param context
	 * @param beanPerson
	 */
	public static void saveUserInfo(Context context, BeanPerson beanPerson) {
		if (beanPerson == null || context == null) {
			return;
		}
		SharedPreferences sharedPreferences = context.getSharedPreferences(Constant.KEY.LOCAL_LOGIN_USER_INFO,
				Context.MODE_PRIVATE);
		Editor editor = sharedPreferences.edit();
		editor.putBoolean(BeanPerson.COLUMN_LOGIN, beanPerson.isLogin());
		editor.putString(BeanPerson.COLUMN_USER_ID, beanPerson.getUserId());
		editor.putString(BeanPerson.COLUMN_REALNAME, beanPerson.getRealname());
		editor.putString(BeanPerson.COLUMN_USER_CODE, beanPerson.getUserCode());
		editor.putString(BeanPerson.COLUMN_TEACHER_ID, beanPerson.getTeacherId());
		editor.putString(BeanPerson.COLUMN_GRADE, beanPerson.getGrade());
		editor.putString(BeanPerson.COLUMN_SUBJECT, beanPerson.getSubject());
		editor.putString(BeanPerson.COLUMN_MOBILE_PHONE, beanPerson.getMobilePhone());
		editor.putString(BeanPerson.COLUMN_EMAIL, beanPerson.getEmail());
		editor.putString(BeanPerson.COLUMN_CORR_ADDRESS, beanPerson.getCorrAddress());
		editor.putString(BeanPerson.COLUMN_PHOTO_PATH, beanPerson.getPhotoPath());
		editor.commit();
	}

	/**
	 * 获取本地用户信息
	 * 
	 * @param context
	 * @return
	 */
	public static BeanPerson getLoginUserInfo(Context context) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(Constant.KEY.LOCAL_LOGIN_USER_INFO,
				Context.MODE_PRIVATE);
		if (sharedPreferences == null) {
			return null;
		}
		BeanPerson beanPerson = new BeanPerson();
		beanPerson.setLogin(sharedPreferences.getBoolean(BeanPerson.COLUMN_LOGIN, false));
		beanPerson.setUserId(sharedPreferences.getString(BeanPerson.COLUMN_USER_ID, ""));
		beanPerson.setRealname(sharedPreferences.getString(BeanPerson.COLUMN_REALNAME, ""));
		beanPerson.setUserCode(sharedPreferences.getString(BeanPerson.COLUMN_USER_CODE, ""));
		beanPerson.setTeacherId(sharedPreferences.getString(BeanPerson.COLUMN_TEACHER_ID, ""));
		beanPerson.setGrade(sharedPreferences.getString(BeanPerson.COLUMN_GRADE, ""));
		beanPerson.setSubject(sharedPreferences.getString(BeanPerson.COLUMN_SUBJECT, ""));
		beanPerson.setMobilePhone(sharedPreferences.getString(BeanPerson.COLUMN_MOBILE_PHONE, ""));
		beanPerson.setEmail(sharedPreferences.getString(BeanPerson.COLUMN_EMAIL, ""));
		beanPerson.setCorrAddress(sharedPreferences.getString(BeanPerson.COLUMN_CORR_ADDRESS, ""));
		beanPerson.setPhotoPath(sharedPreferences.getString(BeanPerson.COLUMN_PHOTO_PATH, ""));
		return beanPerson;
	}

	/**
	 * 判断用户是否已登陆
	 * 
	 * @param context
	 * @return
	 */
	public static boolean ifLogin(Context context) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(Constant.KEY.LOCAL_LOGIN_USER_INFO,
				Context.MODE_PRIVATE);
		if (sharedPreferences == null) {
			return false;
		}
		return sharedPreferences.getBoolean(BeanPerson.COLUMN_LOGIN, false);
	}
}
